package chapter07

import scala.math.Ordering

/**
 * 单词计数：将集合中出现的相同的单词，
 * 进行计数，取计数排名前三的结果
 * List((hello,5), (scala,2), (from,2))
 */
object Test19 {
  def main(args: Array[String]): Unit = {
    val list: List[String] = List(
      "hello",
      "hello word",
      "hello scala",
      "hello flink from scala",
      "hello spack from",
    )


    //去除空格
    val strings: List[String] = list.flatMap(_.split(" "))

    //分组
    val stringToStrings: Map[String, List[String]] = strings.groupBy(word => word)

    //收集
    val tuples: List[(String, Int)] = stringToStrings.map(kv => (
      kv._1, kv._2.size
    ))
      .toList
      .sortBy(_._2)(Ordering[Int].reverse)
      .take(3)

    println(tuples)
  }
  }
